package org.micode.libs.servlet.base;

import lombok.extern.slf4j.Slf4j;
import org.micode.common.domain.ApiResult;
import org.micode.common.domain.DataPage;
import org.micode.common.domain.base.BaseEntity;
import org.micode.common.domain.base.BaseQuery;
import org.micode.common.domain.base.IUserCache;
import org.micode.common.domain.vo.EditObjVO;

import java.util.List;
import java.util.function.Function;

/**
 * 通用业务逻辑基类
 */
@Slf4j
public abstract class BaseWebController
        extends AbstractWebController {

    protected ApiResult<Integer> deleteForIds(Function<EditObjVO<List<Long>>, Integer> serviceDeleteFunc,
                                              List<Long> delIds) {
        IUserCache currentUser = getCurrentUserCache(request);

        EditObjVO<List<Long>> editObjVO =
                new EditObjVO<>(delIds,
                        null == currentUser ? 0 : currentUser.getUserId(),
                        getLoginClientApp(request),
                        getLoginClientIp(request));
        return invokeMethod(serviceDeleteFunc, editObjVO);
    }

    protected <DTO extends BaseEntity, QRY extends BaseQuery> ApiResult<DataPage<DTO>> listForQuery(
            Function<QRY, DataPage<DTO>> listFunc, QRY dataQuery) {
        IUserCache user = currentLoginUser(request);
        copyLoginUserFields(user, dataQuery.getExample());
        return invokeMethod(listFunc, dataQuery);
    }

    protected <DTO extends BaseEntity> ApiResult<DTO> insertTheDTO(
            Function<DTO, DTO> saveFunc, DTO theDTO) {
        fillLoginFields(theDTO);
        return invokeMethod(saveFunc, theDTO);
    }

    protected <DTO extends BaseEntity> ApiResult<Integer> updateTheDTO(
            Function<DTO, Integer> saveFunc, DTO theDTO) {
        fillLoginFields(theDTO);
        return invokeMethod(saveFunc, theDTO);
    }

    protected <K> void fillLoginFields(K theObj) {
        fillLoginFields(request, theObj);
    }

}
